﻿#ifndef ENCODE_H
#define ENCODE_H
#include <iostream>
#include <assert.h>
#include <QObject>

namespace Encode {
    unsigned char toHex(unsigned char x)
    {
        return  x > 9 ? x + 55 : x + 48;
    }

    unsigned char fromHex(unsigned char x)
    {
        unsigned char y=0;
        if (x >= 'A' && x <= 'Z') y = x - 'A' + 10;
        else if (x >= 'a' && x <= 'z') y = x - 'a' + 10;
        else if (x >= '0' && x <= '9') y = x - '0';
        else assert(0);
        return y;
    }

    QByteArray urlEncode(const QByteArray& str)
    {
        QByteArray strTemp = "";
        size_t length = str.length();
        for (size_t i = 0; i < length; i++)
        {

            if (isalnum((unsigned char)str.data()[i]) ||
                (str.data()[i] == '-') ||
                (str.data()[i] == '_') ||
                (str.data()[i] == '.') ||
                (str.data()[i] == '~'))
                strTemp += str.data()[i];
            else if (str.data()[i] == ' ')
                strTemp += "+";
            else
            {
                strTemp += '%';
                strTemp += toHex((unsigned char)str.data()[i] >> 4);
                strTemp += toHex((unsigned char)str.data()[i] % 16);
            }
        }
        return strTemp;
    }

    QByteArray urlDecode(const QByteArray& str)
    {
        QByteArray strTemp = "";
        size_t length = str.length();
        for (size_t i = 0; i < length; i++)
        {
            if (str.data()[i] == '+') strTemp += ' ';
            else if (str.data()[i] == '%')
            {
                assert(i + 2 < length);
                unsigned char high = fromHex((unsigned char)str.data()[++i]);
                unsigned char low = fromHex((unsigned char)str.data()[++i]);
                strTemp += high*16 + low;
            }
            else strTemp += str.data()[i];
        }
        return strTemp;
    }
}



#endif // ENCODE_H
